/*! Bing Search Helper v1.0.0 - requires jQuery v1.7.2 */

$(function() {
	// Attaches a click handler to the button.

	$('.form-search').submit(function(e) {
		e.preventDefault();
		// Clear the results div.
		$('#resultados').empty();
		var query = $('#palabra_dibujada').val();
		var serviceOp = 'Image';

		if (query) {
			search(query, serviceOp);
			APP.palabra_dibujada = query;
			jQuery.post('setea_palabra.php', {palabra_dibujada: query});
                }

	});

	// Performs the search.

	function search(query, serviceOp) {
		// Establish the data to pass to the proxy.
		var data = { q: query, sop: serviceOp, market: 'es-XL' };
		// Calls the proxy, passing the query, service operation and market.
		$.getJSON('bing_proxy.php', data, function(obj) {
			if (obj.d !== undefined) {
				var items = obj.d.results;
				for (var k = 0, len = items.length; k < 4; k++) {
					var item = items[k];
					showImageResult(item);
				}
			}
		});

	}

	// Shows one item of Image result.

	function showImageResult(item) {

		var a = document.createElement('a');
		// Make the object that the user clicks the thumbnail image.
			// Create an image element and set its source to the thumbnail.
			var i = document.createElement('img');
			i.src = item.Thumbnail.MediaUrl;
			i.className = "img-rounded";

		// Append the anchor tag and paragraph with the title to the results div.

		$('#resultados').append(i);
	}

});